package controllers

import (
	"gitee.com/igolang/imoney/internal/common/httpResp"
	commonTools "gitee.com/igolang/imoney/internal/common/tools"
	"gitee.com/igolang/imoney/internal/common/tools/storage"
	"github.com/gin-gonic/gin"
	"net/http"
)

type common struct {
}

var Common = &common{}

func (c *common) Upload(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	form, err := ctx.MultipartForm()
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	files := make([]*storage.FileInfo, 0)
	for _, v := range form.File {
		for _, fh := range v {
			file, err := storage.Upload(fh)
			if err != nil {
				httpResp.ErrorResponse(err, r)
				return
			}
			files = append(files, file)
		}

	}

	r.Data = files
}

func (c *common) Profile(ctx *gin.Context) {
	name := ctx.Param("filename")
	r := httpResp.Response()
	if name == "" {
		httpResp.ErrorResponse(httpResp.ErrCodeInvalidParams, r)
		ctx.JSON(http.StatusNotFound, r)
		return
	}

	filename, err := storage.Get(name)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		ctx.JSON(http.StatusNotFound, r)
		return
	}
	// 开始处理
	if err = commonTools.OutFile(ctx, filename); err != nil {
		httpResp.ErrorResponse(err, r)
		ctx.JSON(http.StatusNotFound, r)
		return
	}
}

func (c *common) Resource(ctx *gin.Context) {
	r := httpResp.Response()
	var req struct {
		Resource string `json:"resource" form:"resource" binding:"required"`
	}

	if err := ctx.ShouldBind(&req); err != nil {
		httpResp.ErrorResponse(err, r)
		ctx.JSON(http.StatusNotFound, r)
		return
	}
	name := req.Resource
	if name == "" {
		httpResp.ErrorResponse(httpResp.ErrCodeInvalidParams, r)
		ctx.JSON(http.StatusNotFound, r)
		return
	}
	filename, err := storage.Get(name)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		ctx.JSON(http.StatusNotFound, r)
		return
	}
	err = commonTools.DownloadFile(ctx, filename)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		ctx.JSON(http.StatusNotFound, r)
		return
	}
}
